<template>
  <view class="container">
    <uv-form labelPosition="left" :model="model1" :rules="rules" ref="form">
      <uv-form-item label="密码长度" prop="len">
        <uv-input v-model="model1.len" border="none"></uv-input>
      </uv-form-item>
    </uv-form>
    <uv-button @click="refresh" text="刷新" type="primary"></uv-button>
    <uv-divider text="转换结果"></uv-divider>
    <uv-form>
      <uv-form-item v-for="(item, key) in arr" :key="key" borderBottom>
        <uv-input :value="item" disabled border="none">
          <template v-slot:suffix>
            <uv-button @click="copyPwd(item)" text="复制" type="success" size="mini"></uv-button>
          </template>
        </uv-input>
      </uv-form-item>
    </uv-form>
  </view>
</template>

<script>
export default {
  data() {
    return {
      arr: [],
      model1: {
        len: 16,
        total: 20
      },
      rules: {
        len: {
          type: "number",
          required: true,
          message: "请填写数字"
        }
      }
    }
  },
  created() {
    this.arr = this.generateRandomStrings(this.model1.len, this.model1.total)
  },
  watch: {
    "model1.len": function (newVal) {
      this.arr = this.generateRandomStrings(newVal, this.model1.total)
    }
  },
  methods: {
    generateRandomStrings(count, numStrings) {
      // 定义可能的字符集合
      const digits = "0123456789"
      const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
      const allChars =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;:'\",.<>?/"

      // 参数设置
      count = count || 10 // 每个字符串的长度
      numStrings = numStrings || 7 // 总共生成的字符串数量

      // 生成只含数字的字符串
      const digitString = generateString(digits, count)
      // 生成只含字母的字符串
      const letterString = generateString(letters, count)
      // 生成5个无限制的字符串
      const mixedStrings = []
      for (let i = 0; i < numStrings - 2; i++) {
        mixedStrings.push(generateString(allChars, count))
      }

      // 返回结果数组
      return [digitString, letterString, ...mixedStrings]

      // 辅助函数：生成指定长度和字符集的随机字符串
      function generateString(charSet, length) {
        let result = ""
        for (let i = 0; i < length; i++) {
          const index = Math.floor(Math.random() * charSet.length)
          result += charSet.charAt(index)
        }
        return result
      }
    },
    copyPwd(val) {
      uni.setClipboardData({
        data: val,
        success: function () {
          uni.showToast({
            title: "复制成功",
            icon: "none"
          })
        }
      })
    },
    refresh() {
      this.arr = this.generateRandomStrings(this.model1.len, this.model1.total)
    }
  }
}
</script>

<style lang="scss" scoped>
.my-component {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background-color: #f0f0f0;
}
.container {
  padding: 0 15px;
}
</style>
